package com.duo.websocket;

import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: Xrx
 * @Description: WebSocket服务
 * @CreateTime: 2023/7/10 20:25
 */
@Component
@ServerEndpoint("/ws/{sid}")
public class WebSocketServer {

    // 存放回话对象
    private static final Map<String, Session> sessionMap = new HashMap<>();

    @OnOpen
    public void onOpen(Session session, @PathParam("sid") String sid) {
        System.out.println("客户端：" + sid + "建立连接");
        sessionMap.put(sid, session);
    }

    @OnMessage
    public void onMessage(String message, @PathParam("sid") String sid) {
        System.out.println("收到来自客户端：" + sid + "的信息：" + message);
    }

    /**
     * 连接关闭调用的方法
     * @param sid
     */
    @OnClose
    public void onClose(@PathParam("sid") String sid) {
        System.out.println("连接断开：" + sid);
        sessionMap.remove(sid);
    }

    /**
     * 群发消息
     * @param message
     */
    public void sendToAllClient(String message) {
        sessionMap.forEach((sid, session) -> {
            // 服务器向客户端发送消息
            session.getAsyncRemote().sendText(message);
        });
    }



}
